package com.kai.admin.security.handler;

import com.kai.admin.enums.AdminErrorCodeConstants;
import com.kai.admin.exception.LoginException;
import com.kai.common.data.Result;
import com.kai.common.util.IpAddressUtil;
import com.kai.common.util.WebUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * <p>
 * 登录失败处理程序
 * </p>
 *
 * @author weijk
 * @since 2023/7/13
 */
@Slf4j
@Component
public class AuthenticationFailureHandlerImpl implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        String ip = IpAddressUtil.get(httpServletRequest);
        log.error("登录失败, url=[{}], ip=[{}], msg=[{}]", httpServletRequest.getRequestURI(), ip, e.getMessage(), e);

        // 统一返回400 Bad Request
        httpServletResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        if (e instanceof LoginException) {
            LoginException loginException = (LoginException) e;
            WebUtil.writeJson(Result.fail(loginException.getErrorCode(), loginException.getMessage()), httpServletResponse);
            return;
        }

        WebUtil.writeJson(Result.fail(AdminErrorCodeConstants.LOGIN_FAILURE), httpServletResponse);
    }
}
